//
//  RequestUtils.swift
//  AnJiBei
//
//  Created by 赵鑫 on 15/10/27.
//  Copyright © 2015年 赵鑫. All rights reserved.
//

import Foundation
import Alamofire
import SwiftyJSON

import UIKit
class RequestUtils {
    //
    static let FAILURE_MESSAGE = "请求失败"
    
    static func requestJson(url: String, parameter: String, requestDelegate:RequestDelegate) {

        let params = ["data":parameter]
        
       // printLog("params", message: params)
        debugPrint(params)
        
        Alamofire.request(.POST, url, parameters: params)
            .responseJSON{response in
                PrintUntils.printLog("params", message: params)
                PrintUntils.printLog("url", message: url)
                PrintUntils.printLog("response", message: response)
                if response.result.error != nil {
                    
                
                    PrintUntils.printLog("error", message: response.result.error)
                
                    PrintUntils.printLog("Jsonerror", message: RequestUtils.FAILURE_MESSAGE)
                    
                    let alterView = UIAlertView(title: "提示", message: "服务器有问题", delegate: self, cancelButtonTitle: "确定")
                    alterView.show()
                    
                }
                
                else {
                    PrintUntils.printLog("response", message: response)
                    
                    let jsonString = JSON(response.result.value!)
                    
                    
                    
                    PrintUntils.printLog("jsonString", message: jsonString)
                    
                    let code = jsonString["code"].string!
                    PrintUntils.printLog("code", message: code)
                    let message = jsonString["message"].string!
                    PrintUntils.printLog("meassge", message: message)
                    
                    
                    switch code {
                    
                        //解析json失败
                    case Constant.REQUEST_FAILURE_CODE:
                        //printLog("FAILURE", message: message)
                        debugPrint("requestFailure")
                        requestDelegate.requestFailure!(message)
                        
                    case Constant.REQUEST_SUCCESS_CODE:
                        let arrayJson = jsonString["contents"]
                        
                        //请求成功，有数据
                        if arrayJson.count != 0 {
                        
                            debugPrint("requestSuccess")
                            requestDelegate.requestSuccess!(arrayJson.object, message: message)
                            
                        }
                            //无数据
                        else {
                        
                            debugPrint("requestDataNull")
                            requestDelegate.requestDataNull!(message)
                        }
                        //请求超时
                    case Constant.REQUEST_TIMEOUT_CODE:
                        debugPrint("timeOut")
                        requestDelegate.requestTimeOut!(message)
                        
                    default:
                        break
                        
                    }

 
                }
                
        }
        
    }
    

    /**
     组装文件上传头部和参数
     
     :param: data       图片
     :param: url        请求地址
     :param: parameters 请求参数
     
     :returns: NSMutableURLRequest
     */
    func requestWithURL(data: NSData, url: NSURL, parameters: Dictionary<String, String>!) -> NSMutableURLRequest {
        let mutableURLRequest = NSMutableURLRequest(URL: url)
        mutableURLRequest.HTTPMethod = "POST"
        
        let mutableData = NSMutableData()
        let boundary = "Boundary+\(arc4random())\(arc4random())"
        var bodyStr = "\n--" + boundary + "\n"
        mutableData.appendData(bodyStr.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
        if let p = parameters {
            for (k, v) in p {
                bodyStr = "Content-Disposition: form-data; name=\"\(k)\"\n\n\(v)"
                mutableData.appendData(bodyStr.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
                let bodyStr = "\n--" + boundary + "\n"
                mutableData.appendData(bodyStr.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
            }
        }
        bodyStr = "Content-Disposition: form-data; name=\"pictrue\"; filename=\"pictrue.png\""
        mutableData.appendData(bodyStr.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
        bodyStr = "Content-Type: application/octet-stream\n\n"
        mutableData.appendData(bodyStr.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
        mutableData.appendData(data)
        bodyStr = "\n"
        mutableData.appendData(bodyStr.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
        
        let tailStr = "--\(boundary)--\n"
        mutableData.appendData(tailStr.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
        
        mutableURLRequest.HTTPBody = mutableData
        bodyStr = "multipart/form-data; boundary=\(boundary)"
        mutableURLRequest.setValue(bodyStr, forHTTPHeaderField: "Content-Type")
        
        return mutableURLRequest
    }
    
    // 文件上传
    func uploadFileToPath(data: NSData, url: NSURL, parameters: Dictionary<String, String>!, success: (JSON) -> Void, failure: (NSError) -> Void) {
        
        let mutableURLRequest = requestWithURL(data, url: url, parameters: parameters)
        Alamofire.request(mutableURLRequest).response{ (request,response, json, error) -> Void in

            debugPrint(request)
            debugPrint(response)
            debugPrint(json)
            debugPrint(error)
            
        }
        
    }

    
}
